import { defineComponent, ref, computed, watchEffect, provide, createVNode } from 'vue';
import { Value } from '../../inner/Value.js';
import TimePane from './TimePane.js';
import TimeRange from './TimeRange.js';
import Dropdown from '../../Dropdown/index.js';
import dayjs from 'dayjs';
import formFieldRef from '../../use/formFieldRef.js';
import { FeatherClock } from 'cui-vue-icons/feather';

const index = /* @__PURE__ */ defineComponent({
  name: 'TimePicker',
  props: {
    type: {
      type: String,
      default: 'time'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    theme: {
      type: String,
      default: 'light'
    },
    size: {
      type: String,
      default: ''
    },
    clearable: {
      type: Boolean,
      default: false
    },
    align: {
      type: String,
      default: 'bottomLeft'
    },
    format: {
      type: String,
      default: 'HH:mm:ss'
    },
    modelValue: {
      type: [String, Date, Array],
      default: undefined
    },
    prepend: {
      type: [String, Object],
      default: ''
    },
    disabledTime: {
      type: Function
    },
    minuteStep: {
      type: Number
    },
    secondStep: {
      type: Number
    },
    hourStep: {
      type: Number
    },
    header: {
      type: [String, Array]
    },
    footer: {
      type: [String, Array]
    },
    seperator: {
      type: String
    },
    transfer: {
      type: Boolean
    },
    trigger: {
      type: Function
    },
    placeholder: {
      type: String
    },
    asFormField: {
      type: Boolean,
      default: true
    }
  },
  emits: ['change', 'update:modelValue'],
  setup(props, {
    emit
  }) {
    const value = formFieldRef(props, emit, props.modelValue ?? props.type === 'timeRange' ? [] : '');
    // 内部value，防止类似form调用的setValue后重复执行effect
    const v = ref(value.value);
    const visible = ref(false);
    const align = props.align ?? 'bottomLeft';
    const format = props.format ?? 'HH:mm:ss';
    const seperator = props.seperator || '~';
    const header = props.header ?? (props.type === 'timeRange' ? ['开始时间', '结束时间'] : undefined);
    const classList = computed(() => ({
      'cm-time-picker': true,
      'cm-time-picker-disabled': props.disabled,
      [`cm-time-picker-${props.theme}`]: props.theme,
      [`cm-time-picker-${props.size}`]: props.size,
      'cm-time-picker-clearable': !props.disabled && props.clearable && value.value !== '' && value.value.length !== 0,
      'cm-time-picker-open': open
    }));
    watchEffect(() => {
      let val = value.value;
      if (val) {
        if (typeof val === 'string') {
          if (props.type === 'timeRange') {
            const arr = val.split(seperator);
            val = [dayjs(dayjs().format('YYYY-MM-DD ') + arr[0]).toDate(), dayjs(dayjs().format('YYYY-MM-DD ') + arr[1]).toDate()];
          } else {
            val = dayjs(dayjs().format('YYYY-MM-DD ') + val).toDate();
          }
        } else if (val instanceof Array) {
          if (val[0] && typeof val[0] === 'string') {
            val = [dayjs(dayjs().format('YYYY-MM-DD ') + val[0]).toDate(), dayjs(dayjs().format('YYYY-MM-DD ') + val[1]).toDate()];
          }
        }
      }
      v.value = val;
    });
    const onSelect = (type, num, name) => {
      const now = new Date();
      const origin = v.value || (props.type === 'timeRange' ? [now, now] : now);
      if (props.type === 'timeRange' && !origin.length) {
        origin.push(now);
        origin.push(now);
      }
      let val;
      if (name === 'start') {
        val = origin[0];
      } else if (name === 'end') {
        val = origin[1];
      } else {
        val = origin;
      }
      if (type === 'hour') {
        val.setHours(num);
      }
      if (type === 'minute') {
        val.setMinutes(num);
      }
      if (type === 'second') {
        val.setSeconds(num);
      }
      if (props.type === 'timeRange') {
        let newVal = [];
        if (name === 'start') {
          newVal = [new Date(val), origin[1]];
        }
        if (name === 'end') {
          newVal = [origin[0], new Date(val)];
        }
        if (newVal[0].getTime() > newVal[1].getTime()) {
          newVal = [newVal[1], newVal[0]];
        }
        value.value = newVal;
        props.onChange && props.onChange(newVal);
      } else {
        const ret = new Date(val);
        value.value = ret;
        emit('change', ret);
      }
    };
    const onClear = () => {
      value.value = '';
      emit('change', '');
    };
    const text = computed(() => {
      const val = v.value;
      if (val) {
        if (typeof val === 'string') {
          return val;
        } else {
          if (props.type === 'timeRange') {
            if (val.length) {
              if (typeof val[0] === 'string') {
                return val.join(seperator);
              }
              return [dayjs(val[0]).format(format), dayjs(val[1]).format(format)].join(seperator);
            } else {
              return '';
            }
          }
          return dayjs(val).format(format);
        }
      }
      return '';
    });
    provide('CMTimepickerContext', {
      onSelect,
      disabledTime: props.disabledTime,
      visible
    });
    return () => createVNode("div", {
      "class": classList.value,
      "x-placement": align,
      "tab-index": "1"
    }, [createVNode(Dropdown, {
      "transfer": props.transfer,
      "align": align,
      "modelValue": visible.value,
      "onUpdate:modelValue": $event => visible.value = $event,
      "trigger": "click",
      "disabled": props.disabled,
      "menu": createVNode("div", {
        "class": "cm-time-picker-wrap"
      }, [props.type === 'timeRange' ? createVNode(TimeRange, {
        "value": v.value,
        "format": format,
        "minuteStep": props.minuteStep,
        "secondStep": props.secondStep,
        "hourStep": props.hourStep,
        "header": header,
        "footer": props.footer
      }, null) : createVNode(TimePane, {
        "value": v.value,
        "format": format,
        "minuteStep": props.minuteStep,
        "secondStep": props.secondStep,
        "hourStep": props.hourStep,
        "header": header,
        "footer": props.footer
      }, null)])
    }, {
      default: () => [!props.trigger ? createVNode(Value, {
        "prepend": props.prepend,
        "text": text.value,
        "onClear": onClear,
        "clearable": props.clearable,
        "placeholder": props.placeholder,
        "disabled": props.disabled,
        "size": props.size,
        "icon": createVNode(FeatherClock, null, null)
      }, null) : props.trigger && props.trigger()]
    })]);
  }
});

export { index as default };
